import jwt
import datetime
from flask import current_app

# 生成JWT
def generate_token(user_id, expires_hours=1):
    payload = {
        'userId': user_id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=expires_hours)
    }
    secret = current_app.config['SECRET_KEY']
    token = jwt.encode(payload, secret, algorithm='HS256')
    return token

# 解析JWT
def decode_token(token):
    secret = current_app.config['SECRET_KEY']
    try:
        payload = jwt.decode(token, secret, algorithms=['HS256'])
        return payload
    except jwt.ExpiredSignatureError:
        return None  # token过期
    except jwt.InvalidTokenError:
        return None  # token无效

# 从token获取user_id
def get_user_id_from_token(token):
    if token and token.startswith('Bearer '):
        token = token.split(' ')[1] # 提取 Bearer 后面的 token 部分
    # 可选：去除 token 前后可能的空白字符
    # if token:
    #     token = token.strip()

    payload = decode_token(token)
    if payload and 'userId' in payload:
        return payload['userId']
    return None